package com.xsdl.giteespringbootautoconfigure.util;

import org.springframework.http.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class HttpUtil {

    public static String sendPostRequest(RestTemplate restTemplate, String url, Map<String, Object> body) {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 创建HttpEntity对象
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        // 发送POST请求
        try {
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,
                    String.class);
            // 返回响应体
            return response.getBody();
        } catch (HttpClientErrorException e) {
            return e.getResponseBodyAsString();
        }
    }

    public static String sendGetRequest(RestTemplate restTemplate, String url) {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 创建HttpEntity对象
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(headers);
        // 发送GET请求
        try {
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity,
                    String.class);
            // 返回响应体
            return response.getBody();
        } catch (HttpClientErrorException e) {
            return e.getResponseBodyAsString();
        }
    }

}
